home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / CONNECTION.PY < prev    next >
Encoding:
Python Source  |  2000-10-06  |  19.5 KB  |  575 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. """Database connection support
  65.  
  66. $Id: Connection.py,v 1.34.12.6 2000/10/06 15:20:13 brian Exp $"""
  67. __version__='$Revision: 1.34.12.6 $'[11:-2]
  68.  
  69. from cPickleCache import PickleCache
  70. from POSException import ConflictError, ExportError
  71. from cStringIO import StringIO
  72. from cPickle import Unpickler, Pickler
  73. from ExtensionClass import Base
  74. from time import time
  75. import Transaction, string, ExportImport, sys, traceback, TmpStore
  76. from zLOG import LOG, ERROR
  77. from coptimizations import new_persistent_id
  78.  
  79. ExtensionKlass=Base.__class__
  80.  
  81. class HelperClass: pass
  82. ClassType=type(HelperClass)
  83.  
  84. class Connection(ExportImport.ExportImport):
  85.     """Object managers for individual object space.
  86.  
  87.     An object space is a version of collection of objects.  In a
  88.     multi-threaded application, each thread get's it's own object
  89.     space.
  90.  
  91.     The Connection manages movement of objects in and out of object storage.
  92.     """
  93.     _tmp=None
  94.     _debug_info=()
  95.     _opened=None
  96.  
  97.     # Experimental. Other connections can register to be closed
  98.     # when we close by putting something here.
  99.  
  100.     def __init__(self, version='', cache_size=400,
  101.                  cache_deactivate_after=60):
  102.         """Create a new Connection"""
  103.         self._version=version
  104.         self._cache=cache=PickleCache(self, cache_size, cache_deactivate_after)
  105.         self._incrgc=self.cacheGC=cache.incrgc
  106.         self._invalidated=d={}
  107.         self._invalid=d.has_key
  108.         self._committed=[]
  109.  
  110.     def _breakcr(self):
  111.         try: del self._cache
  112.         except: pass
  113.         try: del self._incrgc
  114.         except: pass
  115.         try: del self.cacheGC
  116.         except: pass
  117.  
  118.     def __getitem__(self, oid,
  119.                     tt=type(()), ct=type(HelperClass)):
  120.         cache=self._cache
  121.         if cache.has_key(oid): return cache[oid]
  122.  
  123.         __traceback_info__ = (oid)
  124.         p, serial = self._storage.load(oid, self._version)
  125.         __traceback_info__ = (oid, p)
  126.         file=StringIO(p)
  127.         unpickler=Unpickler(file)
  128.         unpickler.persistent_load=self._persistent_load
  129.  
  130.         try:
  131.             object = unpickler.load()
  132.         except:
  133.             raise "Could not load oid %s, pickled data in traceback info may\
  134.             contain clues" % (oid)
  135.  
  136.         klass, args = object
  137.  
  138.         if type(klass) is tt:
  139.             module, name = klass
  140.             klass=self._db._classFactory(self, module, name)
  141.         
  142.         if (args is None or
  143.             not args and not hasattr(klass,'__getinitargs__')):
  144.             object=klass.__basicnew__()
  145.         else:
  146.             object=apply(klass,args)
  147.             if klass is not ExtensionKlass:
  148.                 object.__dict__.clear()
  149.  
  150.         object._p_oid=oid
  151.         object._p_jar=self
  152.         object._p_changed=None
  153.         object._p_serial=serial
  154.  
  155.         cache[oid]=object
  156.         if oid=='\0\0\0\0\0\0\0\0': self._root_=object # keep a ref
  157.         return object
  158.  
  159.     def _persistent_load(self,oid,
  160.                         d={'__builtins__':{}},
  161.                         tt=type(()), st=type(''), ct=type(HelperClass)):
  162.  
  163.         __traceback_info__=oid
  164.  
  165.         cache=self._cache
  166.  
  167.         if type(oid) is tt:
  168.             # Quick instance reference.  We know all we need to know
  169.             # to create the instance wo hitting the db, so go for it!
  170.             oid, klass = oid
  171.             if cache.has_key(oid): return cache[oid]
  172.  
  173.             if type(klass) is tt:
  174.                 module, name = klass
  175.                 try: klass=self._db._classFactory(self, module, name)
  176.                 except:
  177.                     # Eek, we couldn't get the class. Hm.
  178.                     # Maybe their's more current data in the
  179.                     # object's actual record!
  180.                     return self[oid]
  181.             
  182.             object=klass.__basicnew__()
  183.             object._p_oid=oid
  184.             object._p_jar=self
  185.             object._p_changed=None
  186.             
  187.             cache[oid]=object
  188.  
  189.             return object
  190.  
  191.         if cache.has_key(oid): return cache[oid]
  192.         return self[oid]
  193.  
  194.     def _setDB(self, odb):
  195.         """Begin a new transaction.
  196.  
  197.         Any objects modified since the last transaction are invalidated.
  198.         """     
  199.         self._db=odb
  200.         self._storage=s=odb._storage
  201.         self.new_oid=s.new_oid
  202.         self._cache.invalidate(self._invalidated)
  203.         self._opened=time()
  204.  
  205.         return self
  206.  
  207.     def abort(self, object, transaction):
  208.         """Abort the object in the transaction.
  209.  
  210.         This just deactivates the thing.
  211.         """
  212.         self._cache.invalidate(object._p_oid)
  213.  
  214.     def cacheFullSweep(self, dt=0): self._cache.full_sweep(dt)
  215.     def cacheMinimize(self, dt=0): self._cache.minimize(dt)
  216.  
  217.     __onCloseCallbacks=()
  218.     def onCloseCallback(self, f):
  219.         self.__onCloseCallbacks=self.__onCloseCallbacks+(f,)
  220.  
  221.     def close(self):
  222.         self._incrgc() # This is a good time to do some GC
  223.         db=self._db
  224.  
  225.         # Call the close callbacks.
  226.         for f in self.__onCloseCallbacks:
  227.             try: f()
  228.             except:
  229.                 f=getattr(f, 'im_self', f)
  230.                 LOG('ZODB',ERROR, 'Close callback failed for %s' % f,
  231.                     error=sys.exc_info())
  232.         self.__onCloseCallbacks=()
  233.         self._db=self._storage=self._tmp=self.new_oid=self._opened=None
  234.         self._debug_info=()
  235.         # Return the connection to the pool.
  236.         db._closeConnection(self)
  237.                         
  238.     def commit(self, object, transaction, _type=type, _st=type('')):
  239.         oid=object._p_oid
  240.         invalid=self._invalid
  241.         if oid is None or object._p_jar is not self:
  242.             oid = self.new_oid()
  243.             object._p_jar=self
  244.             object._p_oid=oid
  245.  
  246.         elif object._p_changed:
  247.             if invalid(oid) or invalid(None): raise ConflictError, oid
  248.             self._invalidating.append(oid)
  249.  
  250.         else:
  251.             # Nothing to do
  252.             return
  253.  
  254.         stack=[object]
  255.  
  256.         # Create a special persistent_id that passes T and the subobject
  257.         # stack along:
  258.         #
  259.         # def persistent_id(object,
  260.         #                   self=self,
  261.         #                   stackup=stackup, new_oid=self.new_oid):
  262.         #     if (not hasattr(object, '_p_oid') or
  263.         #         type(object) is ClassType): return None
  264.         # 
  265.         #     oid=object._p_oid
  266.         # 
  267.         #     if oid is None or object._p_jar is not self:
  268.         #         oid = self.new_oid()
  269.         #         object._p_jar=self
  270.         #         object._p_oid=oid
  271.         #         stackup(object)
  272.         # 
  273.         #     klass=object.__class__
  274.         # 
  275.         #     if klass is ExtensionKlass: return oid
  276.         #     
  277.         #     if hasattr(klass, '__getinitargs__'): return oid
  278.         # 
  279.         #     module=getattr(klass,'__module__','')
  280.         #     if module: klass=module, klass.__name__
  281.         #     
  282.         #     return oid, klass
  283.         
  284.         file=StringIO()
  285.         seek=file.seek
  286.         pickler=Pickler(file,1)
  287.         pickler.persistent_id=new_persistent_id(self, stack.append)
  288.         dbstore=self._storage.store
  289.         file=file.getvalue
  290.         cache=self._cache
  291.         get=cache.get
  292.         dump=pickler.dump
  293.         clear_memo=pickler.clear_memo
  294.  
  295.  
  296.         version=self._version
  297.         
  298.         while stack:
  299.             object=stack[-1]
  300.             del stack[-1]
  301.             oid=object._p_oid
  302.             serial=getattr(object, '_p_serial', '\0\0\0\0\0\0\0\0')
  303.             if invalid(oid): raise ConflictError, oid
  304.             klass = object.__class__
  305.         
  306.             if klass is ExtensionKlass:
  307.                 # Yee Ha!
  308.                 dict={}
  309.                 dict.update(object.__dict__)
  310.                 del dict['_p_jar']
  311.                 args=object.__name__, object.__bases__, dict
  312.                 state=None
  313.             else:
  314.                 if hasattr(klass, '__getinitargs__'):
  315.                     args = object.__getinitargs__()
  316.                     len(args) # XXX Assert it's a sequence
  317.                 else:
  318.                     args = None # New no-constructor protocol!
  319.         
  320.                 module=getattr(klass,'__module__','')
  321.                 if module: klass=module, klass.__name__
  322.                 __traceback_info__=klass, oid, self._version
  323.                 state=object.__getstate__()
  324.         
  325.             seek(0)
  326.             clear_memo()
  327.             dump((klass,args))
  328.             dump(state)
  329.             p=file(1)
  330.             s=dbstore(oid,serial,p,version,transaction)
  331.             if s:
  332.                 # Note that if s is false, then the storage defered the return
  333.                 if _type(s) is _st:
  334.                     # normal case
  335.                     object._p_serial=s
  336.                     object._p_changed=0
  337.                 else:
  338.                     # defered returns
  339.                     for oi, s in s:
  340.                         if _type(s) is not _st: raise s
  341.                         o=get(oi, oi)
  342.                         if o is not oi:
  343.                             o._p_serial=s
  344.                             o._p_changed=0
  345.                         elif oi == oid:
  346.                             object._p_serial=s
  347.                             object._p_changed=0
  348.  
  349.             try: cache[oid]=object
  350.             except:
  351.                 # Dang, I bet its wrapped:
  352.                 if hasattr(object, 'aq_base'):
  353.                     cache[oid]=object.aq_base
  354.                 else:
  355.                     raise
  356.  
  357.     def commit_sub(self, t,
  358.                    _type=type, _st=type(''), _None=None):
  359.         tmp=self._tmp
  360.         if tmp is _None: return
  361.         src=self._storage
  362.         self._storage=tmp
  363.         self._tmp=_None
  364.  
  365.         tmp.tpc_begin(t)
  366.         
  367.         load=src.load
  368.         store=tmp.store
  369.         dest=self._version
  370.         get=self._cache.get
  371.         oids=src._index.keys()
  372.         invalidating=self._invalidating
  373.         invalidating[len(invalidating):]=oids
  374.         
  375.         for oid in oids:
  376.             data, serial = load(oid, src)
  377.             s=store(oid, serial, data, dest, t)
  378.             if s:
  379.                 if _type(s) is _st:
  380.                     o=get(oid, _None)
  381.                     if o is not _None: o._p_serial=s
  382.                 else:
  383.                     for oid, s in s:
  384.                         if _type(s) is not _st: raise s
  385.                         o=get(oid, _None)
  386.                         if o is not _None: o._p_serial=s
  387.                         
  388.  
  389.     def abort_sub(self, t):
  390.         tmp=self._tmp
  391.         if tmp is None: return
  392.         src=self._storage
  393.         self._tmp=None
  394.         self._storage=tmp
  395.         self._cache.invalidate(src._index.keys())
  396.  
  397.     def db(self): return self._db
  398.  
  399.     def getVersion(self): return self._version
  400.         
  401.     def invalidate(self, oid):
  402.         """Invalidate a particular oid
  403.  
  404.         This marks the oid as invalid, but doesn't actually invalidate
  405.         it.  The object data will be actually invalidated at certain
  406.         transaction boundaries.
  407.         """
  408.         self._invalidated[oid]=1
  409.  
  410.     def modifiedInVersion(self, oid):
  411.         try: return self._db.modifiedInVersion(oid)
  412.         except KeyError:
  413.             return self._version
  414.  
  415.     def root(self): return self['\0\0\0\0\0\0\0\0']
  416.  
  417.     def setstate(self,object):
  418.         try:
  419.             oid=object._p_oid
  420.             #invalid=self._invalid
  421.             #if invalid(oid) or invalid(None): raise ConflictError, oid
  422.             p, serial = self._storage.load(oid, self._version)
  423.             file=StringIO(p)
  424.             unpickler=Unpickler(file)
  425.             unpickler.persistent_load=self._persistent_load
  426.             unpickler.load()
  427.             state = unpickler.load()
  428.  
  429.             if hasattr(object, '__setstate__'):
  430.                 object.__setstate__(state)
  431.             else:
  432.                 d=object.__dict__
  433.                 for k,v in state.items(): d[k]=v
  434.  
  435.             object._p_serial=serial
  436.  
  437.         except:
  438.             t, v =sys.exc_info()[:2]
  439.             LOG('ZODB',ERROR, "Couldn't load state for %s" % `oid`,
  440.                 error=sys.exc_info())
  441.             raise
  442.  
  443.     def oldstate(self, object, serial):
  444.         oid=object._p_oid
  445.         p = self._storage.loadSerial(oid, serial)
  446.         file=StringIO(p)
  447.         unpickler=Unpickler(file)
  448.         unpickler.persistent_load=self._persistent_load
  449.         unpickler.load()
  450.         return  unpickler.load()
  451.  
  452.     def setklassstate(self, object,
  453.                       tt=type(()), ct=type(HelperClass)):
  454.         try:
  455.             oid=object._p_oid
  456.             __traceback_info__=oid
  457.             p, serial = self._storage.load(oid, self._version)
  458.             file=StringIO(p)
  459.             unpickler=Unpickler(file)
  460.             unpickler.persistent_load=self._persistent_load
  461.     
  462.             copy = unpickler.load()
  463.     
  464.             klass, args = copy
  465.     
  466.             if klass is not ExtensionKlass:
  467.                 LOG('ZODB',ERROR,
  468.                     "Unexpected klass when setting class state on %s"
  469.                     % getattr(object,'__name__','(?)'))
  470.                 return
  471.             
  472.             copy=apply(klass,args)
  473.             object.__dict__.clear()
  474.             object.__dict__.update(copy.__dict__)
  475.     
  476.             object._p_oid=oid
  477.             object._p_jar=self
  478.             object._p_changed=0
  479.             object._p_serial=serial
  480.         except:
  481.             LOG('ZODB',ERROR, 'setklassstate failed', error=sys.exc_info())
  482.             raise
  483.  
  484.     def tpc_abort(self, transaction):
  485.         self._storage.tpc_abort(transaction)
  486.         cache=self._cache
  487.         cache.invalidate(self._invalidated)
  488.         cache.invalidate(self._invalidating)
  489.  
  490.     def tpc_begin(self, transaction, sub=None):
  491.         if self._invalid(None): # Some nitwit invalidated everything!
  492.             raise ConflictError, "transaction already invalidated"
  493.         self._invalidating=[]
  494.  
  495.         if sub:
  496.             # Sub-transaction!
  497.             _tmp=self._tmp
  498.             if _tmp is None:
  499.                 _tmp=TmpStore.TmpStore(self._version)
  500.                 self._tmp=self._storage
  501.                 self._storage=_tmp
  502.                 _tmp.registerDB(self._db, 0)
  503.  
  504.         self._storage.tpc_begin(transaction)
  505.  
  506.     def tpc_vote(self, transaction,
  507.                  _type=type, _st=type('')):
  508.         try: vote=self._storage.tpc_vote
  509.         except: return
  510.         s=vote(transaction)
  511.         if s:
  512.             get=self._cache.get
  513.             for oid, s in s:
  514.                 o=get(oid, oid)
  515.                 if o is not oid:
  516.                     if _type(s) is not _st: raise s
  517.                     o._p_serial=s
  518.                     o._p_changed=0
  519.         
  520.  
  521.     def tpc_finish(self, transaction):
  522.         self._storage.tpc_finish(transaction, self.tpc_finish_)
  523.         self._cache.invalidate(self._invalidated)
  524.         self._incrgc() # This is a good time to do some GC
  525.  
  526.     def tpc_finish_(self):
  527.         invalidate=self._db.invalidate
  528.         for oid in self._invalidating: invalidate(oid, self)
  529.  
  530.     def sync(self):
  531.         get_transaction().abort()
  532.         self._cache.invalidate(self._invalidated)
  533.         self._incrgc() # This is a good time to do some GC
  534.  
  535.     def getDebugInfo(self): return self._debug_info
  536.     def setDebugInfo(self, *args): self._debug_info=self._debug_info+args
  537.  
  538.  
  539.     ######################################################################
  540.     # Just plain weird. Don't try this at home kids.
  541.     def exchange(self, old, new):
  542.         oid=old._p_oid
  543.         new._p_oid=oid
  544.         new._p_jar=self
  545.         new._p_changed=1
  546.         get_transaction().register(new)
  547.         self._cache[oid]=new
  548.         
  549. class tConnection(Connection):
  550.  
  551.     def close(self):
  552.         self._breakcr()
  553.  
  554.